import React from 'react'
import { Spin, message } from 'antd'
import moment from 'moment'
import ReactEchartsCore from 'echarts-for-react/lib/core'
import * as echarts from 'echarts/core'
import { BarChart, LineChart } from 'echarts/charts'
import { TooltipComponent, GridComponent } from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'
import PropTypes from 'prop-types'
import Component, { mapStateToProps, mapDispatchToProps } from '@components/Component'
import { connect } from 'react-redux'
import style from './YearTrend.module.less'
import NumberSelector from '../../NumberSelector'
import classNames from 'classnames'
echarts.use([BarChart, LineChart, CanvasRenderer, TooltipComponent, GridComponent])
class YearTrend extends Component {
  state = {
    acceptAndClosureYear: moment().year(),
    moneyYear: moment().year(),
    yearAcceptAndClosreLoading: false,
    yearMoneyLoading: false,
    activeChart: '立结案件趋势',
    yearAcceptNum: 0,
    yearAntAcceptNum: 0,
    yearClosureNum: 0,
    yearAcceptList: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    yearAntAcceptList: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    yearClosureList: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    yearMoneyList: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    yearTotalMoney: 0
  }

  formatMoney (money) {
    const m = String(money)
    if (!/^\d*$/.test(m)) {
      return m
    }
    return m.replace(/\B(?=(\d{3})+(?!\d))/g, ',')
  }

  // 根据年获取开始时间戳和结束时间戳
  getBeginAndEndTime (year) {
    const m = moment(`${year}-01-01`)
    const begintime = Math.floor(m.valueOf() / 1000)
    m.add(1, 'y')
    m.subtract(1, 's')
    const endtime = Math.floor(m.valueOf() / 1000)
    return {
      begintime,
      endtime
    }
  }

  // 获取全年月份收案数据
  getYearAccept (begintime, endtime) {
    return this.$get('/api/xapc/casestat', {
      begintime,
      endtime,
      type: 'accept_datetime',
      group: 'month',
      field: 'caseno,amountsum,feesum'
    }).then(res => {
      if (res.status === 1) {
        return res.data
      } else {
        message.warning(res.message)
      }
    })
  }

  // 获取全年月份收案数据
  getYearAntAccept (begintime, endtime) {
    return this.$get('/api/xapc/casestat', {
      begintime,
      endtime,
      type: 'counter_accept_datetime',
      group: 'month',
      field: 'caseno,amountsum,feesum'
    }).then(res => {
      if (res.status === 1) {
        return res.data
      } else {
        message.warning(res.message)
      }
    })
  }

  // 获取全年结案数据
  getYearClosure (begintime, endtime) {
    return this.$get('/api/xapc/casestat', {
      begintime,
      endtime,
      type: 'closure_datetime',
      group: 'month',
      field: 'caseno,amountsum,feesum'
    }).then(res => {
      if (res.status === 1) {
        return res.data
      } else {
        message.warning(res.message)
      }
    })
  }

  // 获取年立结案数据
  getYearAcceptAndClosure () {
    const { begintime, endtime } = this.getBeginAndEndTime(this.state.acceptAndClosureYear)
    this.setState({ yearAcceptAndClosreLoading: true })
    Promise.all([this.getYearAccept(begintime, endtime), this.getYearClosure(begintime, endtime), this.getYearAntAccept(begintime, endtime)])
      .then(res => {
        this.setState({ yearAcceptAndClosreLoading: false })
        const accept = res[0]
        const closure = res[1]
        const antAccept = res[2]
        this.setState({
          yearAcceptNum: accept.total.caseno,
          yearAntAcceptNum: antAccept.total.caseno,
          yearClosureNum: closure.total.caseno,
          yearAcceptList: accept.list.map(li => li.caseno),
          yearAntAcceptList: antAccept.list.map(li => li.caseno),
          yearClosureList: closure.list.map(li => li.caseno)
        })
      }).catch(() => this.setState({ yearAcceptAndClosreLoading: false }))
  }

  getAcceptChartOptions () {
    return {
      grid: {
        left: 40,
        right: 0,
        top: 10,
        bottom: 30
      },
      tooltip: {},
      xAxis: {
        type: 'category',
        data: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],
        axisLine: {
          lineStyle: {
            color: '#ddd'
          }
        },
        axisTick: {
          show: false
        },
        axisLabel: {
          color: '#8f949e'
        }
      },
      yAxis: {
        type: 'value',
        axisLine: {
          show: false
        },
        axisTick: {
          show: false
        },
        axisLabel: {
          color: '#8f949e'
        },
        splitLine: {
          lineStyle: {
            type: 'dashed'
          }
        },
        minInterval: 1
      },
      series: [{
        name: '收案数',
        data: this.state.yearAcceptList,
        type: 'bar',
        barWidth: '10%',
        color: '#0039BF'
      },
      {
        name: '反请求收案数',
        data: this.state.yearAntAcceptList,
        type: 'bar',
        barWidth: '10%',
        color: '#FF9B37'
      }, {
        name: '结案数',
        data: this.state.yearClosureList,
        type: 'bar',
        barWidth: '10%',
        color: '#6fddf6'
      }]
    }
  }

  getTotalMoneyOption () {
    const width = String(this.state.yearTotalMoney).length * 10
    return {
      grid: {
        left: width < 40 ? 40 : width,
        right: 0,
        top: 10,
        bottom: 30
      },
      tooltip: {
        trigger: 'axis'
      },
      xAxis: {
        type: 'category',
        data: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],
        axisLine: {
          lineStyle: {
            color: '#ddd'
          }
        },
        axisTick: {
          show: false
        },
        axisLabel: {
          color: '#8f949e'
        }
      },
      yAxis: {
        type: 'value',
        axisLine: {
          show: false
        },
        axisTick: {
          show: false
        },
        axisLabel: {
          color: '#8f949e'
        },
        splitLine: {
          lineStyle: {
            type: 'dashed'
          }
        },
        minInterval: 1,
        max: function (value) {
          if (value.max <= 10) {
            return 10
          }
          const b = Math.pow(10, String(parseInt(value.max)).length - 1)
          return Math.ceil(value.max / b) * b
        }
      },
      series: [{
        name: '总标的',
        data: this.state.yearMoneyList,
        type: 'line',
        color: '#FF9B37',
        smooth: true,
        areaStyle: { color: '#fff7ef' }
      }]
    }
  }

  // 获取全年仲裁标的
  getYearMoney () {
    const { begintime, endtime } = this.getBeginAndEndTime(this.state.moneyYear)
    this.setState({ yearMoneyLoading: true })
    return this.$get('/api/xapc/casestat', {
      begintime,
      endtime,
      type: 'docket_datetime',
      group: 'month',
      field: 'caseno,amountsum,feesum'
    }).then(res => {
      this.setState({ yearMoneyLoading: false })
      if (res.status === 1) {
        this.setState({
          yearTotalMoney: res.data.total.amountsum || 0,
          yearMoneyList: res.data.list.map(li => li.amountsum)
        })
      } else {
        message.warning(res.message)
      }
    }).catch(() => this.setState({ yearMoneyLoading: false }))
  }

  // 查看表格详情
  chartClickHandle (e) {
    const monthList = ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月']
    const index = monthList.indexOf(e.name)
    const date = moment(`${this.state.acceptAndClosureYear}-01-01 00:00:00`)
    const beginTime = moment(date)
    beginTime.add(index, 'M')
    const endTime = moment(beginTime)
    endTime.add(1, 'M')
    endTime.subtract(1, 's')
    const formData = {
      beginTime,
      endTime
    }
    switch (e.seriesName) {
      case '立案数':
        formData.type = 'docket_datetime'
        break
      case '收案数':
        formData.type = 'accept_datetime'
        break
      case '反请求收案数':
        formData.type = 'counter_accept_datetime'
        break
      case '结案数':
        formData.type = 'closure_datetime'
        break
      case '总标的':
        formData.type = 'docket_datetime'
        break
    }
    this.props.addWindow({ id: 'AllCaseManage', title: '仲裁案件列表', componentName: 'AllCaseManage', forceRefresh: true, meta: { formData } })
  }

  componentDidMount () {
    this.getYearAcceptAndClosure()
    this.getYearMoney()
  }

  render () {
    const { activeChart } = this.state
    const isAccept = activeChart === '立结案件趋势'
    const onEvents = { click: this.chartClickHandle.bind(this) }
    return (
      <div>
        <div className={style['foot-toggle-title']}>
          <div className={isAccept ? [style['toggle-title-btn'], style.active].join(' ') : style['toggle-title-btn']} onClick={() => this.setState({ activeChart: '立结案件趋势' })}>立结案件趋势</div>
          <div className={!isAccept ? [style['toggle-title-btn'], style.active].join(' ') : style['toggle-title-btn']} onClick={() => this.setState({ activeChart: '仲裁标的趋势' })}>仲裁标的趋势</div>
        </div>
        <div className={style['foot-block']} style={{ display: isAccept ? 'block' : 'none' }}>
          <div className={style['foot-block__header']}>
            <NumberSelector value={this.state.acceptAndClosureYear} onChange={v => this.setState({ acceptAndClosureYear: v }, () => this.getYearAcceptAndClosure())} />
            <div className={style['foot-block__tag']}>
              <div className={style['tag-header']}>
                <span className={style.square} />
                <span>收案数</span>
              </div>
              <div className={style['tag-content']}>
                <span>{this.state.yearAcceptNum}</span>
                <span className={style.unit}>件</span>
              </div>
            </div>
            <div className={style['foot-block__tag']}>
              <div className={style['tag-header']}>
                <span className={classNames(style.square, style.warning)} />
                <span>反请求收案数</span>
              </div>
              <div className={style['tag-content']}>
                <span>{this.state.yearAntAcceptNum}</span>
                <span className={style.unit}>件</span>
              </div>
            </div>
            <div className={style['foot-block__tag']}>
              <div className={style['tag-header']}>
                <span className={[style.square, style.vice].join(' ')} />
                <span>结案数</span>
              </div>
              <div className={style['tag-content']}>
                <span>{this.state.yearClosureNum}</span>
                <span className={style.unit}>件</span>
              </div>
            </div>
          </div>
          <div className={style['foot-block__content']}>
            <Spin spinning={this.state.yearAcceptAndClosreLoading}>
              <ReactEchartsCore className={classNames({ [style.hide]: !this.props.ready })} echarts={echarts} onEvents={onEvents} option={this.getAcceptChartOptions()} style={{ width: '100%', height: '264px' }} />
            </Spin>
          </div>
        </div>
        <div className={style['foot-block']} style={{ display: !isAccept ? 'block' : 'none' }}>
          <div className={style['foot-block__header']}>
            <NumberSelector value={this.state.moneyYear} onChange={v => this.setState({ moneyYear: v }, () => this.getYearMoney())} />
            <div className={style['foot-block__tag']}>
              <div className={style['tag-header']}>
                <span className={[style.square, style.warning].join(' ')} />
                <span>总标的</span>
              </div>
              <div className={style['tag-content']}>
                <span>{this.formatMoney(this.state.yearTotalMoney)}</span>
                <span className={style.unit}>元</span>
              </div>
            </div>
          </div>
          <div className={style['foot-block__content']}>
            <Spin spinning={this.state.yearMoneyLoading}>
              <ReactEchartsCore className={classNames({ [style.hide]: !this.props.ready })} echarts={echarts} onEvents={onEvents} option={this.getTotalMoneyOption()} style={{ width: '100%', height: '264px' }} />
            </Spin>
          </div>
        </div>
      </div>
    )
  }
}

YearTrend.propTypes = {
  ready: PropTypes.bool
}

YearTrend.defaultProps = {
  ready: false
}

const mapState = mapStateToProps(function (state) {
  return {
    userInfo: state.basic.userInfo
  }
})

const mapDispatch = mapDispatchToProps(function (dispatch) {
  return {

  }
})

export default connect(mapState, mapDispatch)(YearTrend)
